package com.learn.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.learn.core.domain.LOrganization;
import com.learn.core.mapper.LOrganizationMapper;
import com.learn.core.service.ILOrganizationService;
import com.learn.framework.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @auther CodeGenerator
 * @create 2021-03-11 23:46:37
 * @describe 组织机构表服务实现类
 */
@Service
public class LOrganizationServiceImpl extends BaseServiceImpl<LOrganizationMapper, LOrganization> implements ILOrganizationService {

    @Autowired
    LOrganizationMapper lOrganizationMapper;

    @Override
    public List<LOrganization> queryLOrganizationAll(QueryWrapper<LOrganization> queryWrapper) {
        List<LOrganization> treeMenus =new  ArrayList<>();
        List<LOrganization> lOrganizationList = lOrganizationMapper.selectList(queryWrapper);
        // 查询树结构
        for(LOrganization lOrganization : getRootNode(lOrganizationList)) {
            lOrganization=buildChilTree(lOrganization,lOrganizationList);
            treeMenus.add(lOrganization);
        }
        return treeMenus;
    }

    //递归，建立子树形结构
    private LOrganization buildChilTree(LOrganization pNode,List<LOrganization> menuList){
        List<LOrganization> chilMenus =new ArrayList<>();
        for(LOrganization menuNode : menuList) {
            if(menuNode.getParentNode() == pNode.getOrganizationId()) {
                chilMenus.add(buildChilTree(menuNode,menuList));
            }
        }
        pNode.setChilLOrganization(chilMenus);
        return pNode;
    }

    //获取根节点
    private List<LOrganization> getRootNode(List<LOrganization> menuList) {
        List<LOrganization> rootMenuLists =new  ArrayList<LOrganization>();
        for(LOrganization menuNode : menuList) {
            if(menuNode.getParentNode() == 0) {
                rootMenuLists.add(menuNode);
            }
        }
        return rootMenuLists;
    }
}
